package com.terry.bootdemo.api.controller;

import com.terry.bootdemo.api.Result.TokenResult;
import com.terry.bootdemo.api.apidao.ApiTokenDao;
import com.terry.bootdemo.api.apidao.ApiUserInfosDao;
import com.terry.bootdemo.api.entity.ApiConnUser;
import com.terry.bootdemo.api.entity.Token;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/jwt")
public class ApiTokenController {
    @Autowired ApiTokenDao apiTokenDao;
    @Autowired ApiUserInfosDao apiUserInfosDao;
    @RequestMapping(value = "/token",method = {RequestMethod.GET,RequestMethod.POST})
 public TokenResult generatorToken(@RequestParam String appId, @RequestParam String appSecrete){
    TokenResult tokenResult=new TokenResult();
    if(appId==null || appId.trim()==""){
        tokenResult.setFlag(false);
        tokenResult.setMsg("appid"+appId+"is not found");
    }
    if(appSecrete==null || appSecrete.trim()==""){
        tokenResult.setFlag(false);
        tokenResult.setMsg("appsecrete"+appSecrete+"is not found");
    }
        ApiConnUser apiConnUser=apiUserInfosDao.findOne(new Specification<ApiConnUser>() {
            @Override
            public Predicate toPredicate(Root<ApiConnUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("appId"),appId));
                return null;
            }
        });

    if(apiConnUser==null){
        tokenResult.setFlag(false);
        tokenResult.setMsg("appid不存在");

    }else if(!new String(apiConnUser.getAppSecrete()).equals(appSecrete.replace(" ","+"))){
        tokenResult.setFlag(false);
        tokenResult.setMsg("appsecrete不存在");
    }else{
        Token token=apiTokenDao.findOne(new Specification<Token>() {
            @Override
            public Predicate toPredicate(Root<Token> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("appId"),appId));
                return null;
            }
        });
        String tokenStr=null;
        //生产jwttoken
        if(token==null){
            tokenStr=createToken(appId);
            token=new Token();
            token.setAppId(apiConnUser.getAppId());
            token.setBuildTime(String.valueOf(System.currentTimeMillis()));
            token.setToken(tokenStr.getBytes());
            apiTokenDao.save(token);
        }else{ //判断是否时间超时
           long buildTime= Long.valueOf(token.getBuildTime());
           long currentTime=System.currentTimeMillis();
           long seconds= TimeUnit.MILLISECONDS.toSeconds(currentTime-buildTime);
           if(seconds>0 && seconds <7200){
                tokenStr=new String(token.getToken());
           }else{
               //token超时
               tokenStr=createToken(appId);
               token=new Token();
               token.setBuildTime(String.valueOf(System.currentTimeMillis()));
               token.setToken(tokenStr.getBytes());
               apiTokenDao.save(token);
           }
        }
        tokenResult.setToken(tokenStr);
    }
    return  tokenResult;
 }

 public String createToken(String appId){
     Date now=new Date(System.currentTimeMillis());
     Date expirationTime=new Date(now.getTime()+7200000);
 return Jwts.builder().setSubject(appId).setIssuedAt(now).setIssuer("terryj buider").setExpiration(expirationTime).signWith(SignatureAlgorithm.HS256,"terryjAuthy1.0.0").compact();

 }
}
